﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using System;
public class Joystic : MonoBehaviour, IPointerUpHandler, IDragHandler, IPointerDownHandler
{
    private float MaxDistence = 100f;//最大距离
    RectTransform rect;
    private Vector2 V2;
    private void Awake()
    {
        rect = ToolUnity.FindGameObject(gameObject, "joystickwin").GetComponent<RectTransform>();
    }
    public void OnDrag(PointerEventData eventData)
    {
        if (Vector3.Distance(eventData.position, transform.position) < MaxDistence)
        {
            //虚拟键跟随鼠标
            rect.position = eventData.position;
        }
        else
        {
            //计算出鼠标和原点之间的向量
            Vector3 dir = new Vector3(eventData.position.x, eventData.position.y, 0) - transform.position;
            //这里dir.normalized是向量归一化的意思，实在不理解你可以理解成这就是一个方向，就是原点到鼠标的方向，乘以半径你可以理解成在原点到鼠标的方向上加上半径的距离
            rect.position = transform.position + dir.normalized * MaxDistence;
        }
        V2 = rect.localPosition.normalized;
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        rect.position = transform.position;
        V2 = Vector2.zero;
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        rect.position = eventData.position;
    }

    //方向
    public Vector2 Vector()
    {
        return V2;
    }
}
